package top.frsf;

import top.frsf.bullet.Bullet;
import top.frsf.envir.Blast;
import top.frsf.envir.Wall;
import top.frsf.tank.Bot;
import top.frsf.tank.PlayerOne;
import top.frsf.tank.PlayerTwo;
import top.frsf.tank.TankObj;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Random;

/**
 * @BelongsProject: TankWar1
 * @BelongsPackage: top.frsf
 * @Author: FRSF
 * @CreateTime: 2022-09-03  08:38
 * @Description: 游戏主页
 * @Version: 1.0
 */
public class GamePanel extends JFrame {
    // 窗体尺寸
    int width = 800;
    int height = 600;

    // 游戏模式: 0 游戏未开始，1 单人模式，2 双人模式，3 局域网对战, 4 游戏胜利，5 游戏失败，6 游戏暂停
    int state = 0;
    int aState = 1;

    // 双缓存图片
    Image offScreenImage = null;
    // 模式选择指针图片
    Image selectImage = Toolkit.getDefaultToolkit().getImage("src/main/resources/images/tank.jpg");
    int selectImageY = 150;


    // 敌方tank数量
    int emergeNum = 0;
    // 重绘帧数统计
    public int flashNum = 0;

    // 游戏结束标准
    boolean gameOver = false;

    // delay
    boolean delay = false;


    /* PlayerOne */
    PlayerOne playerOne = new PlayerOne("src/main/resources/playerone/right.jpg", 125, 510, this,
            "src/main/resources/playerone/up.jpg", "src/main/resources/playerone/down.jpg",
            "src/main/resources/playerone/left.jpg", "src/main/resources/playerone/right.jpg");

    PlayerTwo playerTwo = new PlayerTwo("src/main/resources/playertwo/right.png", 500, 510, this,
            "src/main/resources/playertwo/up.png", "src/main/resources/playertwo/down.png",
            "src/main/resources/playertwo/left.png", "src/main/resources/playertwo/right.png");

    /* Bullet List*/
    public ArrayList<Bullet> bulletList = new ArrayList<>();

    /* Bot List*/
    public ArrayList<Bot> botList = new ArrayList<>();

    /* Remove playerone List */
    public ArrayList<Bullet> removeListBullets = new ArrayList<>();

    /* Player List */
    public ArrayList<TankObj> playerList = new ArrayList<>();

    /* Wall List */
    public ArrayList<Wall> wallList = new ArrayList<>();

    /* Main Wall */
    public ArrayList<Wall> mainList = new ArrayList<>();

    /* blast List */
    public ArrayList<Blast> blastList = new ArrayList<>();


    // 窗体初始化启动方法
    public void launch() {
        setTitle("Tank WarⅠ");
        setSize(width, height);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        setVisible(true);

        // 添加键盘监视器
        this.addKeyListener(new KeyMonitor());

        /* 地图初始化 */
        mapInit();

        /* 重绘刷新 */
        while (true) {

            if (gameOver) {
                new DelaySec().start();
                if (delay) {
                    state = 0;
                    flashMemory();
                }
            } else {
                /* 批量添加电脑tank */
                if (flashNum % 100 == 1 && emergeNum < 10) {
                    Random random = new Random();
                    int rnum = random.nextInt(680) + 60;
                    int cnum = random.nextInt(480) + 60;
                    botList.add(new Bot("src/main/resources/bot/right.png", rnum, cnum, this,
                            "src/main/resources/bot/up.png", "src/main/resources/bot/down.png",
                            "src/main/resources/bot/left.png", "src/main/resources/bot/right.png"));
                    emergeNum++;
                }

                /* 游戏胜利判定 */
                if (botList.size() == 0 && emergeNum == 10) {
                    state = 4;
                    gameOver = true;
                }

                /* 游戏失败判定 */
                if (flashNum % 100 == 1) {
                    if (playerList.size() == 0 && (state == 1 || state == 2) || mainList.size() == 0) {
                        state = 5;
                        gameOver = true;
                    }
                }
            }


            repaint();
            try {
                Thread.sleep(15);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void paint(Graphics g) {
        // 创建与容器相同大小的Image，用于缓存
        if (offScreenImage == null) {
            offScreenImage = this.createImage(width, height);
        }
        // 获取缓存Image画笔
        Graphics offGraphics = offScreenImage.getGraphics();

        // 背景
        offGraphics.setColor(Color.GRAY);
        offGraphics.fillRect(0, 0, width, height);

        // 启动页文字样式
        offGraphics.setColor(Color.BLACK);
        offGraphics.setFont(new Font(null, Font.BOLD, 20));

        // 判断state与aState，控制游戏开始
        if (state == 0) {
            offGraphics.drawImage(Toolkit.getDefaultToolkit().getImage("src/main/resources/images/back.png"),
                    0, 0, width, height, null);
            // 添加文字
            offGraphics.drawString("选择游戏模式(↑/↓) 进入游戏(enter)", 220, 100);
            offGraphics.setColor(Color.BLUE);
            offGraphics.setFont(new Font("仿宋", Font.BOLD, 50));
            offGraphics.drawString("单人模式", 280, 200);
            offGraphics.drawString("双人模式", 280, 300);
            offGraphics.drawString("局域网对战", 280, 400);

            // 操作指南
            offGraphics.setColor(Color.darkGray);
            offGraphics.setFont(new Font("", Font.BOLD, 20));
            offGraphics.drawString("PlayerOne: WSAD + SPACE", 220, 500);
            offGraphics.drawString("PlayerTwo: ↑↓←→  + 0(NUM)", 220, 530);

            // 绘制游戏选择指针
            offGraphics.drawImage(selectImage, 200, selectImageY, null);

        } else if (state == 1 || state == 2) {

            offGraphics.drawString("单人模式，P键暂停", 10, 50);
            offGraphics.drawString("剩余敌人：" + botList.size(), 600, 50);

            /* 绘制游戏元素 */
            // 玩家tank
            for (TankObj tankObj : playerList) {
                tankObj.paintSelf(offGraphics);
            }

            // 玩家及电脑子弹
            for (Bullet bullet : bulletList) {
                bullet.paintSelf(offGraphics);
            }

            // 电脑tank
            for (Bot bot : botList) {
                bot.paintSelf(offGraphics);
            }

            // 墙体
            for (Wall wall : wallList) {
                wall.paintSelf(offGraphics);
            }

            // 主基地
            for (Wall wall : mainList) {
                wall.paintSelf(offGraphics);
            }

            // 爆炸特效
            for (Blast blast : blastList) {
                blast.paintSelf(offGraphics);
            }



            /* 删除碰撞元素 */
            bulletList.removeAll(removeListBullets);

            /* 重绘帧数统计 */
            flashNum++;

        } else if (state == 3) {
            offGraphics.drawString("局域网对战正在开发中，敬请期待！", 150, 150);
        } else if (state == 4) {
            offGraphics.drawImage(this.getToolkit().getImage("src/main/resources/envir/win.png"),
                    200, 170, null);
        } else if (state == 5) {
            offGraphics.drawImage(this.getToolkit().getImage("src/main/resources/envir/fail.png"),
                    200, 170, null);
        } else if (state == 6) {
            offGraphics.drawString("游戏暂停，P键盘恢复", 150, 150);
        }


        /* 将缓存区绘制于整个容器父画布中 */
        g.drawImage(offScreenImage, 0, 0, null);

    }

    // 键盘监视器 内部类
    class KeyMonitor extends KeyAdapter {

        private void changeState(boolean up) {
            // 模式选择指针移动 与 模式中间变量
            if (up) {
                if (selectImageY > 150) {
                    selectImageY -= 100;
                }
            } else {
                if (selectImageY < 350) {
                    selectImageY += 100;
                }
            }
            switch (selectImageY) {
                case 150:
                    aState = 1;
                    break;
                case 250:
                    aState = 2;
                    break;
                case 350:
                    aState = 3;
            }
        }

        @Override
        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();
            if (state == 0) {
                // 选择游戏模式控制，避免与PlayerTwo按键冲突
                switch (key) {
                    case KeyEvent.VK_UP:
                        changeState(true);
                        break;
                    case KeyEvent.VK_DOWN:
                        changeState(false);
                        break;
                    case KeyEvent.VK_ENTER:
                        state = aState;
                        if (state == 1) {
                            playerOne.alive = true;
                            playerList.add(playerOne);
                        }
                        if (state == 2) {
                            playerOne.alive = true;
                            playerTwo.alive = true;
                            playerList.add(playerOne);
                            playerList.add(playerTwo);
                        }
                        if (gameOver) {
                            gameOver = false;
                            mapInit();
                            delay = false;
                        }
                        break;
                }
            } else {
                // state != 0
                if (key == KeyEvent.VK_P) {
                    // P键，游戏暂停
                    if (state != 6) {
                        // aState记录原state状态，以便恢复
                        aState = state;
                        state = 6;
                    } else {
                        // 恢复暂停前状态
                        state = aState;
                    }
                } else {
                    // 玩家按键操作
                    playerOne.keyPressed(e);
                    playerTwo.keyPressed(e);
                }
            }

        }

        @Override
        public void keyReleased(KeyEvent e) {
            playerOne.keyReleased(e);
            playerTwo.keyReleased(e);
        }
    }

    public void flashMemory() {
        flashNum = 0;
        emergeNum = 0;
        bulletList.clear();
        botList.clear();
        removeListBullets.clear();
        playerList.clear();
        wallList.clear();
        mainList.clear();
        blastList.clear();
    }

    public void mapInit() {
        /* 地图初始化 */
        for (int i = 0; i < 10; i++) {
            wallList.add(new Wall("src/main/resources/envir/wall.png",
                    100 + i * 60, 150, this));
        }

        for (int i = 0; i < 3; i++) {
            wallList.add(new Wall("src/main/resources/envir/wall.png",
                    280 + i * 60, 480, this));
        }
        wallList.add(new Wall("src/main/resources/envir/wall.png",
                280, 540, this));
        wallList.add(new Wall("src/main/resources/envir/wall.png",
                400, 540, this));

        // 主基地添加
        mainList.add(new Wall("src/main/resources/envir/main.png",
                340, 540, this));
    }

    class DelaySec extends Thread {
        @Override
        public void run() {
            // 设置为冷却状态
            delay = false;
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 解除攻击冷却
            delay = true;
            // 线程终止
            this.stop();
        }
    }

}
